package com.group.Controller;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group.Enity.CarCharge;
import com.group.Enity.User;
import com.group.Service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("userinfo")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @ResponseBody
    @RequestMapping("queryUserInfoAll")
    public JSONObject queryUserInfoAll(Integer page, Integer limit, String type) {
        PageHelper.startPage(page, limit);
        List<User> list = userInfoService.getUsers(type);
        PageInfo pageInfo = new PageInfo<>(list);
        Long len = pageInfo.getTotal();
        List<CarCharge> list_new = pageInfo.getList();

        JSONObject json = new JSONObject();
        json.accumulate("count", len);
        json.accumulate("code", 0);
        json.accumulate("msg", "null");
        json.accumulate("data", list_new);
        return json;
    }

    @ResponseBody
    @RequestMapping("add")
    public String add(@RequestBody User user) {

        String pwdMd5 = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(pwdMd5);
        userInfoService.add(user);
        //System.out.println("username:" + username + ",type:" + type + ",password:" + password);
        return "";
    }

    @ResponseBody
    @RequestMapping("deleteByIds")
    public String deleteByIds(String ids){
        //System.out.println(ids);
        String[] lst = ids.split(",");
        for (int index = 0;index < lst.length;index++)
        {
            int id = Integer.valueOf(lst[index]);
            userInfoService.delete(id);

        }

        JSONObject json=new JSONObject();
        json.accumulate("code",200);
        return json.toString();
    }

    @ResponseBody
    @RequestMapping("update")
    public String update(String oldPwd,String newPwd,int id){

        User user = userInfoService.getUser(id);
        String oldPwdMd5 = DigestUtils.md5DigestAsHex(oldPwd.getBytes() );
        if (user.getPassword().equals(oldPwdMd5))
        {

            String newPwdMd5 = DigestUtils.md5DigestAsHex(newPwd.getBytes() );
            user.setPassword(newPwdMd5);
            userInfoService.update(user);


            return "";
        }else{
            return "";
        }
        //System.out.println(user);
        //System.out.println("old:" + oldPwd +",new:"+newPwd +",id:"+id);
    }

}
